import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form,Table, Button, Input, message, Popconfirm, Divider,Cascader } from 'antd';
import styles from './style.less';

@connect(state => ({
  areaRs: state.areaRs,
}))
@Form.create()
export default class AreaTableForm extends PureComponent {
  state = {
    data: [],
    areaData:[],
  };
  componentDidMount() {

    if (this.props.rsId != undefined && this.props.rsId != "") {
      const rsId = this.props.rsId;
      this.handleInitSearch(rsId,(response)=>{
        this.setState({
          data: response.data.list,
        });
      })
    }
    //查找所有的父节点
    this.handleAreaSearch(null,(response)=>{
      const areaData = this.generateAreaData(response.data.list);
      this.setState({
        areaData:areaData,
      });
    })
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.rsId != undefined && nextProps.rsId != "" && this.props.rsId != nextProps.rsId) {
      const rsId = nextProps.rsId;
      this.handleInitSearch(rsId,(response)=>{
        this.setState({
          data: response.data.list,
        });
      })
    }
  }

  /**
   * 把初始化查询的代码抽离出来
   * @param rsId
   * @param selfCallBack
   */
  handleInitSearch = (rsId,selfCallBack) => {
    const { dispatch } = this.props;
    const params = {
      rsId:rsId
    };
    dispatch({
      type: 'areaRs/listAreaRs',
      payload:params,
      callback:(response) =>{
        selfCallBack(response);
      }
    });
  }
  /**
   * 生成地区树节点的统一方法
   * @param data
   * @returns {Array}
   */
  generateAreaData = (data) => {
    var areasData = [];
    for(var index = 0; index<data.length; index++){
      var curArea = {label: data[index].areaName , value: data[index].id, key:data[index].cityCode,isLeaf:(data[index].leaf == 1 ? true:false)}
      areasData.push(curArea);
    }
    return areasData;
  }
  /**
   * 查找 地区
   * @param pId
   * @param selfCallBack
   */
  handleAreaSearch = (pId,selfCallBack) => {
    const { dispatch } = this.props;
    const params = {
      pId:pId
    };
    dispatch({
      type: 'areaRs/listAreaNodesByPid',
      payload:params,
      callback:(response) =>{
        selfCallBack(response);
      }
    });
  }

  handleAreaRsAdd = (id,rsId,rsFm,areaId,cityCode,sortNum,selfCallBack) => {
    const { dispatch } = this.props;
    const params = {
      id:id,
      rsId:rsId,
      rsFm:rsFm,
      areaId:areaId,
      areaCode:cityCode,
      sortNum:sortNum,
    };
    dispatch({
      type: 'areaRs/saveOrUpdateAreaRs',
      payload:params,
      callback:(response) =>{
        selfCallBack(response);
      }
    });
  }


  //根据key获取当前行
  getRowByKey(key) {
    return this.state.data.filter(item => item.key === key)[0];
  }

  index = 0;
  cacheOriginData = {};

  handleSubmit = (e) => {
    console.log("handleSubmit");
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.dispatch({
          type: 'form/submit',
          payload: values,
        });
      }
    });
  }
  //当前行是否可编辑状态更改
  toggleEditable(e, key) {
    console.log(key);
    e.preventDefault();
    const target = this.getRowByKey(key);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        this.cacheOriginData[key] = { ...target };
      }
      target.editable = !target.editable;
      this.setState({ data: [...this.state.data] });
    }
  }

  /**
   * 删除一行地区数据
   * @param key
   */
  remove(key) {
    const { dispatch } = this.props;
    const newData = this.state.data.filter(item => item.key !== key);
    this.setState({ data: newData });

    const target = this.getRowByKey(key) || {};
    console.info(target);
    const id = target.id == undefined ? null : target.id ;
    if(id != null){
      const params = {
        id:id,
      };
      dispatch({
        type: 'areaRs/delAreaRs',
        payload:params,
        callback:(response) =>{
          if(response.errorCode == "1"){
            message.info("删除成功");
          }
        }
      });
    }else {
      message.info("删除失败");
    }

  }

  /**
   *新建一个地区
   */
  newArea = () => {
    const newData = [...this.state.data];
    newData.push({
      key: `NEW_TEMP_ID_${this.index}`,
      areaId: '',
      cityCode: '',
      rsFm: '',
      editable: true,
      isNew: true,
    });
    this.index += 1;
    this.setState({ data: newData });
  }

  /**
   * 点击Enter键保存
   * @param e
   * @param key
   */
  handleKeyPress(e, key) {
    if (e.key === 'Enter') {
      this.saveRow(e, key);
    }
  }
  /**
   * input改变的时候监听事件
   * @param e
   * @param fieldName
   * @param key
   */
  handleFieldChange(e, fieldName, key) {
    const newData = [...this.state.data];
    const target = this.getRowByKey(key);
    if (target) {
      target[fieldName] = e.target.value;
      this.setState({ data: newData });
    }
  }

  /**
   * 保存地区事件
   * @param e
   * @param key
   */
  saveRow(e, key) {
    const  self = this;
    e.persist();
    // save field when blur input
    if (document.activeElement.tagName === 'INPUT' &&
      document.activeElement !== e.target) {
      return;
    }
    if (this.clickedCancel) {
      this.clickedCancel = false;
      return;
    }
    const target = this.getRowByKey(key) || {};
    if (!target.cityCode || !target.rsFm ) {
      message.error('请填写完整地区信息。');
      e.target.focus();
      return;
    }

    delete target.isNew;
    this.toggleEditable(e, key);

    const id = target.id == undefined ? null : target.id ;
    const areaId = target.areaId;
    const cityCode = target.cityCode;
    const rsFm = target.rsFm;
    const rsId = this.props.rsId;
    const sortNum = this.index +1 ;
    this.handleAreaRsAdd(id,rsId,rsFm,areaId,cityCode,sortNum,(response)=> {
      const rsId = this.props.rsId;
      self.handleInitSearch(rsId,(response)=>{
        self.setState({
          data: response.data.list,
        });
      })
    })
  }





  /**
   * 点击取消按钮事件
   * @param e
   * @param key
   */
  cancel(e, key) {
    this.clickedCancel = true;
    e.preventDefault();
    const target = this.getRowByKey(key);
    if (this.cacheOriginData[key]) {
      Object.assign(target, this.cacheOriginData[key]);
      target.editable = false;
      delete this.cacheOriginData[key];
    }
    this.setState({ data: [...this.state.data] });
  }


  /**
   * 地区更改事件
   * @param value
   * @param selectedOptions
   * @param key
   */
  onAreaChange = (value, selectedOptions,key) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    var cityCode = targetOption.key;
    var areaId = targetOption.value;
    const newData = [...this.state.data];
    const target = this.getRowByKey(key);
    if (target) {
      target["cityCode"] = cityCode;
      target["areaId"] = areaId;
      this.setState({ data: newData });
    }
  }

  /**
   * 加载地区数据
   * @param selectedOptions
   */
  loadAreaData = (selectedOptions) => {
    var self  = this;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    self.handleAreaSearch(targetOption.value,(response)=>{
      targetOption.loading = false;
      const areaData = self.generateAreaData(response.data.list);
      targetOption.children = areaData;
      self.setState({
        areaData: [...this.state.areaData],
      });
    })
  }
  displayAreaRender = (label) => {
    return label[label.length - 1];
  }

  render() {
    const columns = [{
      title: '地区名称',
      dataIndex: 'areaId',
      width: '20%',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Cascader
              placeholder="请选择地区"
              options={this.state.areaData}
              loadData={this.loadAreaData}
              expandTrigger="hover"
              onChange={(value, selectedOptions) => this.onAreaChange(value,selectedOptions,record.key)}
              displayRender={this.displayAreaRender}
              changeOnSelect
            />
          );
        }else {
          return record.areaName;
        }
      },
    }, {
      title: '地区代码',
      dataIndex: 'cityCode',
      width: '20%',
      render: (text, record) => {
        return text;
      },
    }, {
      title: '电台频率',
      dataIndex: 'rsFm',
      width: '40%',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input
              value={text}
              onChange={e => this.handleFieldChange(e, 'rsFm',record.key)}
              onBlur={e => this.saveRow(e,record.key)}
              onKeyPress={e => this.handleKeyPress(e,record.key)}
              placeholder="电台频率"
            />
          );
        }
        return text;
      },
    }, {
      title: '操作',
      dataIndex: 'id',
      render: (text, record) => {
        if (record.editable) {
          if (record.isNew) {
            return (
              <span>
                <a>保存</a>
                <Divider type="vertical" />
                <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.key)}>
                  <a>删除</a>
                </Popconfirm>
              </span>
            );
          }
          return (
            <span>
              <a>保存</a>
              <Divider type="vertical" />
              <a onClick={e => this.cancel(e,record.key)}>取消</a>
            </span>
          );
        }
        return (
          <span>
            <a onClick={e => this.toggleEditable(e,record.key)}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.key)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        );
      },
    }];

    return (
      <div>
        <Table
          columns={columns}
          dataSource={this.state.data}
          pagination={false}
          rowClassName={(record) => {
            return record.editable ? styles.editable : '';
          }}
        />
        <Button
          style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
          type="dashed"
          onClick={this.newArea}
          icon="plus"
        >
          新增地区
        </Button>
      </div>
    );
  }
}
